<template>
  <div class="inner">
    <PageTitle title="复核装包" />
    <div class="ibody">
      <!-- orderfillId存在，则证明扫过了 -->
      <div class="scan-wrap" v-if="status === 0">
        <div class="scan-logo">
          <div class="scan-title">
            扫描包裹单右上角条码&nbsp;&nbsp;开始复核装包
          </div>

          <el-image :src="bgpPng" class="fenjian-d" fit="contain" />
          <el-image :src="scanQpng" class="scan-q" fit="contain" />
          <div class="scan-line updownAnmi" />
        </div>
        <div class="p-input mt2">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-input placeholder="请输入包裹单号" v-model="orderfillNo" />
            </el-col>
            <el-col :span="4">
              <el-button @click="confirmGetPackageDetail">确定</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- 不能直接使用v-else -->
      <div class="result mt20" v-if="status === 1">
        <div class="res-left">
          <div class="drugs">
            <el-table
              :data="packageDetailData.drugs"
              style="width: 100%"
              header-row-class-name="table-header-row"
              :row-class-name="computedRowClass"
            >
              <el-table-column prop="drugId" label="产品编码" />

              <el-table-column prop="address" label="名称">
                <template #default="scope">
                  {{
                    scope.row.commonName +
                    (scope.row.productName ? `(${scope.row.productName})` : "")
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="standard" label="规格" />
              <el-table-column label="数量">
                <template #default="scope">
                  {{ scope.row.hasChecked ? scope.row.amount : "--" }}
                </template>
              </el-table-column>
              <el-table-column label="复核状态">
                <template #default="scope">
                  {{
                    scope.row.drugId === scanResult.drugId
                      ? "复核中"
                      : scope.row.hasChecked
                      ? "已复核"
                      : "待复核"
                  }}
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="info">
            <el-row>
              <el-col :span="12">
                <span class="label">单号</span>
                <span class="value">{{ packageDetailData.orderfillNo }}</span>
              </el-col>
              <el-col :span="12">
                <span class="label">用户</span>
                <span class="value">{{ packageDetailData.recipientName }}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <span class="label">种类</span>
                <span class="value">{{ packageDetailData.drugs.length }}</span>
              </el-col>
              <el-col :span="12">
                <span class="label">数量</span>
                <span class="value">{{ totalDrugsNum }}</span>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="res-right">
          <div
            :class="[
              'scan-title',
              scanResult.drugId || checkFinished ? 'green' : 'danger'
            ]"
          >
            {{
              checkFinished
                ? "本单药品已全部复核"
                : scanResult.drugId
                ? scanResult.commonName +
                  (scanResult.productName
                    ? "（" + scanResult.productName + "）"
                    : "")
                : "扫描药品外包装69码"
            }}
          </div>
          <div class="scan-res" v-if="scanResult.drugId">
            <el-image
              :src="scanResult.outerPackagePicUrl"
              class="scan-drug-img"
              fit="contain"
            />
          </div>
          <div
            class="scan-drug-logo"
            v-if="!checkFinished && !scanResult.drugId"
          >
            <el-image :src="fjScanPng" class="scan-drug-img" fit="contain" />
            <div class="scan-line updownAnmi" />
          </div>
          <div class="scan-drug-logo" v-if="checkFinished">
            <el-image
              :src="finishedPng"
              class="scan-finish-img"
              fit="contain"
            />
          </div>
          <div class="key" v-if="showKeyBoard">
            <div class="title">
              {{ scanResult.amount ? scanResult.amount : "等待输入复核数量…" }}
            </div>
            <div class="dr-keyboard">
              <div
                :class="['dr-knum', activeKey === 7 ? 'active' : '']"
                @click="inputNum(7)"
              >
                <span>7</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 8 ? 'active' : '']"
                @click="inputNum(8)"
              >
                <span>8</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 9 ? 'active' : '']"
                @click="inputNum(9)"
              >
                <span>9</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 4 ? 'active' : '']"
                @click="inputNum(4)"
              >
                <span>4</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 5 ? 'active' : '']"
                @click="inputNum(5)"
              >
                <span>5</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 6 ? 'active' : '']"
                @click="inputNum(6)"
              >
                <span>6</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 1 ? 'active' : '']"
                @click="inputNum(1)"
              >
                <span>1</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 2 ? 'active' : '']"
                @click="inputNum(2)"
              >
                <span>2</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 3 ? 'active' : '']"
                @click="inputNum(3)"
              >
                <span>3</span>
              </div>
              <div
                :class="['dr-knum', activeKey === 0 ? 'active' : '']"
                @click="inputNum(0)"
              >
                <span>0</span>
              </div>
              <div
                :class="[
                  'dr-knum',
                  'dr-kn-delete',
                  activeKey === 'delete' ? 'active' : ''
                ]"
                @click="deleteNum"
              >
                <span>删除</span>
              </div>
              <div
                :class="[
                  'dr-knum',
                  'dr-kn-submit',
                  activeKey === 'submit' ? 'active' : ''
                ]"
                @click="submitCheckForm"
              >
                <span>复核</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="btn-group" v-if="status === 1">
        <div class="wh-btn center info border-none" v-if="!checkFinished">
          {{ pendingDrugsLength - hadCheckedDrugs.length }}种药品等待复核
        </div>
        <div
          class="wh-btn center primary border-solid"
          v-else
          @click="completeCheck"
        >
          完成复核
        </div>
        <div class="wh-btn danger" @click="delayDeal">
          <el-image :src="stopPng" />
          <span>暂缓复核</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import PageTitle from "@/components/PageTitle.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { ref, onMounted, computed, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  getPackageDetailApi,
  completeCheckApi,
  printCheckOrderApi
} from "@/api/check";
import { getDrugsBy69Api } from "@/api/sorting";
import { useUserStoreHook } from "@/store/modules/user";
import { markRaw } from "vue";
import { Warning } from "@element-plus/icons-vue";
import { debounce } from "@/utils/tools";
import bgpPng from "@/assets/img/bgpi.png";
import scanQpng from "@/assets/img/scanQ2.png";
import fjScanPng from "@/assets/img/fj-scan.png";
import stopPng from "@/assets/img/stop.png";
import finishedPng from "@/assets/img/finished.png";
import { myDialog } from "@/components/myDialog";
const userStore = useUserStoreHook();
const warehouseId = userStore.userInfo.warehouseId;
const userId = userStore.userInfo.user;
// 0 还没有扫码包裹单
const status = ref(0);

const showKeyBoard = ref(false);

const activeKey = ref();
const hadCheckedDrugs = ref([]);
const checkFinished = ref(false);

const orderfillNo = ref("");

const scanResult = ref<any>({});

let keyBoardTimeHandler = null;

const packageDetailData = ref<any>({});

const pendingDrugsLength = ref(0);

const totalDrugsNum = ref(0);

const dialogConfirmFn = ref();

function init() {
  status.value = 0;
  showKeyBoard.value = false;
  activeKey.value = "";
  hadCheckedDrugs.value = [];
  checkFinished.value = false;
  orderfillNo.value = "";
  scanResult.value = {};
  packageDetailData.value = {};
  pendingDrugsLength.value = 0;
  totalDrugsNum.value = 0;
}

function computedRowClass({ row, rowIndex }) {
  if (row) {
    if (row.hasChecked) {
      return "table-normal-row complete";
    }
    if (scanResult.value && row.drugId === scanResult.value.drugId) {
      return "table-normal-row green";
    }
  }

  return "table-normal-row";
}

const scanPackage = debounce(
  async function scanPackage(oNo) {
    // 扫码包裹单
    // 扫码药品单
    if (!oNo) {
      return;
    }
    const tempScanResult = await getDrugsBy69Api(warehouseId, oNo);
    // 判定该药品是否属于包裹单药品

    if (!tempScanResult || !tempScanResult.drugId) {
      myDialog.warning({
        message: "药品库中不存在该药品"
      });
      return;
    } else {
      const isInPackage = packageDetailData.value.drugs.find(item => {
        return item.drugId === tempScanResult.drugId;
      });
      if (!isInPackage) {
        myDialog.warning({
          message: "包裹单中不存在该药品，请核对包裹"
        });
        return;
      }
      const hadInput = hadCheckedDrugs.value.find(item => {
        return item.drugId === tempScanResult.drugId;
      });
      if (hadInput) {
        myDialog.warning({
          message: "该药品已经复核过了"
        });

        return;
      }
      orderfillNo.value = "";
      showKeyBoard.value = true;
      scanResult.value = tempScanResult;
    }
  },
  1000,
  true
);

function delayDeal() {
  myDialog.warning({
    message: "将清空本次复核记录并返回初始状态",
    showCancel: true,
    confirmFn: () => {
      init();
      ElMessage({
        type: "info",
        message: "已经清空本次复核记录"
      });
    }
  });
}
function hightKeyBoard(value) {
  clearTimeout(keyBoardTimeHandler);
  activeKey.value = value;
  keyBoardTimeHandler = setTimeout(() => {
    activeKey.value = "";
  }, 100);
}
function inputNum(value) {
  if (
    scanResult.value.amount === "0" ||
    scanResult.value.amount === undefined
  ) {
    scanResult.value.amount = String(value);
  } else {
    scanResult.value.amount = scanResult.value.amount + value;
  }
  hightKeyBoard(value);
}

function deleteNum() {
  // hightKeyBoard("delete");
  if (scanResult.value.amount.length > 0) {
    scanResult.value.amount = scanResult.value.amount.slice(0, -1);
  }
}

function isCheckFinished() {
  hightKeyBoard("submit");
  if (
    packageDetailData.value.drugs &&
    hadCheckedDrugs.value.length === packageDetailData.value.drugs.length
  ) {
    // 商品相同
    checkFinished.value = true;
  }
}

function submitCheckForm() {
  ElMessage.closeAll();
  if (!scanResult.value.amount || scanResult.value.amount === "0") {
    // ElMessage({
    //   message: "复核数量不能为空",
    //   type: "error"
    // });

    // ElMessageBox.alert("复核数量不能为空", "提示", {
    //   confirmButtonText: "确定",
    //   type: "warning",
    //   icon: markRaw(Warning)
    // });
    myDialog.warning({
      message: "复核数量不能为空"
    });

    return;
  }
  // 复核过
  const hadInput = hadCheckedDrugs.value.find(item => {
    return item.drugId === scanResult.value.drugId;
  });
  if (hadInput) {
    myDialog.warning({
      message: "该品种已经复核过了，请核对包裹"
    });

    return;
  }
  // 包裹单中不存在的药品
  const inNeedDrug = packageDetailData.value.drugs.find(item => {
    return item.drugId === scanResult.value.drugId;
  });
  if (!inNeedDrug) {
    myDialog.warning({
      message: "该药品不属于本包裹单，请核对包裹"
    });

    return;
  } else {
    if (Number(scanResult.value.amount) !== Number(inNeedDrug.amount)) {
      myDialog.warning({
        message:
          "复核数量与包裹中的数量不一致，包裹中数量为：" + inNeedDrug.amount
      });
      // ElMessageBox.alert(
      //   "复核的药品数量与包裹中的数量不一致，包裹中的数量为：" +
      //     inNeedDrug.amount,
      //   "提示",
      //   {
      //     confirmButtonText: "确定",
      //     type: "warning",
      //     icon: markRaw(Warning)
      //   }
      // );
      // ElMessage({
      //   message: `复核的数量与包裹单中的数量不一致,包裹单数量为 ${inNeedDrug.amount}`,
      //   type: "error"
      // });
      return;
    }
  }
  inNeedDrug.hasChecked = true;
  hadCheckedDrugs.value.push(
    Object.assign({}, scanResult.value, { amount: inNeedDrug.amount })
  );
  scanResult.value = {};
  // showKeyBoard.value = false;
  // console.log("hadCheckedDrugs:", hadCheckedDrugs);
  isCheckFinished();
}

async function completeCheck() {
  await completeCheckApi(packageDetailData.value.orderfillId, userId);
  // router.push({ path: "/box/list" });
  ElMessage.success("复核完成");
  init();
}

async function printCheckOrder() {
  await printCheckOrderApi(packageDetailData.value.orderfillId);
  ElMessage({
    type: "success",
    message: "打印成功"
  });
}

function confirmGetPackageDetail() {
  const tempOrderfillNo = orderfillNo.value.replace(/^\s*|\s*$/g, "");
  if (status.value === 0) {
    getPackageDetail(tempOrderfillNo);
  } else {
    scanPackage(tempOrderfillNo);
  }
}

async function getPackageDetail(oNo) {
  // const orderfillNo = "123";
  packageDetailData.value = await getPackageDetailApi(oNo);
  if (packageDetailData.value.status === "待复核") {
    pendingDrugsLength.value = packageDetailData.value.drugs.length;
    orderfillNo.value = "";
    packageDetailData.value.drugs.forEach(item => {
      totalDrugsNum.value += item.amount;
    });
    status.value = 1;
  } else {
    myDialog.warning({
      message:
        "只有待复核的包裹才能复核，当前包裹状态为：" +
        packageDetailData.value.status
    });
    // ElMessageBox.alert(
    //   "只有待复核的包裹才能复核，当前包裹状态为：" +
    //     packageDetailData.value.status +
    //     "</span>",
    //   "提示",
    //   {
    //     dangerouslyUseHTMLString: true,
    //     type: "warning",
    //     icon: markRaw(Warning)
    //   }
    // );
  }
  return;
}
// 回车事件

let scanInputNumber = "";
let keyLastTime = 0;

function enterEvent(orderfillNo) {
  console.log("enterEvent orderfillNo:", orderfillNo);
  // 扫码包裹单
  if (status.value === 0) {
    getPackageDetail(orderfillNo);
  } else {
    scanPackage(orderfillNo);
  }
}
function keyDownEvent(event) {
  let gap = 0;
  if (keyLastTime) {
    gap = new Date().getTime() - keyLastTime;
    // 大于50毫秒，则判定为人输入
    if (gap > 50) {
      gap = 0;
      scanInputNumber = "";
    }
  }
  keyLastTime = new Date().getTime();
  if (gap < 50) {
    const theEvent = event || window.event;
    // console.log("theEvent:", theEvent);
    const code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code !== 13 && theEvent.key.length === 1) {
      scanInputNumber += theEvent.key;
    }

    if (code === 13) {
      scanInputNumber = scanInputNumber.replace(/\D*/, "");
      enterEvent(scanInputNumber);
      scanInputNumber = "";
      keyLastTime = 0;
    }
  }
}
onMounted(() => {
  // getPackageDetail();
  document.addEventListener("keydown", keyDownEvent);
});
onUnmounted(() => {
  document.removeEventListener("keydown", keyDownEvent);
});
</script>
<style lang="scss" scoped>
$drugItemWidth: 120px;
.ibody {
  position: relative;
  .scan-wrap {
    position: relative;
    width: 100%;
    height: calc(100vh - 120px);
    .scan-logo {
      margin: auto;
      padding: 10px;
      position: absolute;
      border: 1px dashed #ddd;
      top: 30%;
      left: 50%;
      transform: translateX(-50%);
      .scan-title {
        font-size: 18px;
        font-weight: bold;
        text-align: center;
        color: #3f4254;
      }
      .fenjian-d {
        width: 312px;
        height: 188px;
        margin-top: 20px;
      }
      .scan-q {
        position: absolute;
        right: 22px;
        bottom: 0px;
        width: 174px;
        height: 148px;
      }
      .scan-line {
        position: absolute;
        top: 77px;
        left: 133px;
        width: 174px;
        height: 0px;
        border-bottom: 6px solid #ff7f65;
        opacity: 0;
      }
    }
    .p-input {
      position: absolute;
      width: 300px;
      top: 67%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }
  .result {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    .res-left {
      width: calc(100% - 400px);
      flex-shrink: 0;

      .drugs {
        border-radius: 10px;
        background-color: white;
        padding: 20px;
        :deep(.el-table) {
          .el-table__inner-wrapper {
            &::before {
              display: none;
            }
          }
          .table-normal-row {
            font-size: 18px;
            color: #b5b5c3;
            &.complete {
              color: #3f4254;
            }
            &.green {
              color: #50cd89;
              font-weight: bold;
            }
          }
        }
      }
      .info {
        margin-top: 30px;
        background-color: white;
        border-radius: 10px;
        padding: 20px;
        .el-row {
          height: 50px;
          line-height: 50px;
          border-bottom: 1px dashed #d8d8d8;
          font-size: 18px;
          .label {
            display: inline-block;
            width: 120px;

            color: #b5b5c3;
          }
          .value {
            color: #3f4254;
          }
        }
      }
    }
    .res-right {
      width: 374px;
      border-radius: 10px;
      background: white;
      position: relative;
      flex-shrink: 0;
      overflow: hidden;
      .scan-title {
        height: 50px;
        font-size: 18px;
        font-weight: bold;
        color: #ffffff;
        text-align: center;
        line-height: 50px;
        word-break: keep-all;
        overflow: hidden;

        &.danger {
          background: #ff7f65;
        }
        &.green {
          background: #50cd89;
        }
        .fenjian-d {
          width: 277px;
          height: 175px;
        }
      }
      .scan-res {
        width: 277px;
        height: 277px;
        margin: auto;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        margin-top: 20px;
        margin-bottom: 20px;
        .el-image {
          width: 277px;
          height: 277px;
        }
      }
      .scan-drug-logo {
        margin: auto;
        width: 277px;
        height: 277px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        margin-top: 10px;
        margin-bottom: 10px;

        .scan-drug-img {
          width: 277px;
          height: 277px;
        }
        .scan-finish-img {
          width: 64px;
          height: 64px;
        }
        .scan-line {
          position: absolute;
          top: 0px;
          left: 50px;
          width: 174px;
          height: 0px;
          border-bottom: 6px solid #ff7f65;
          opacity: 0;
        }
      }
      .key {
        margin-top: 20px;
        border-top: 1px dashed #d8d8d8;
        padding: 20px;
        box-sizing: border-box;
        .title {
          height: 32px;
          line-height: 32px;
          text-align: center;
          font-size: 22px;
          font-weight: bold;
          color: #b5b5c3;
        }
        .dr-keyboard {
          display: grid;
          grid-template-rows: repeat(4, 50px);
          grid-template-columns: repeat(3, 100px);
          grid-gap: 10px;
          width: 320px;
          margin: auto;
          margin-top: 20px;
          .dr-knum {
            height: 50px;
            text-align: center;

            border: 1px solid #f5f8fa;
            background: #f5f8fa;

            /* 表单/单元格描边 */
            box-shadow: 0px 1px 0px 0px #e6e6e6;
            border-radius: 4px;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            user-select: none;
            &.active {
              // border-top: 4px solid #bbb;
              // box-shadow: inset 0px 2px 2px 0px #d8d8d8;
              // border-top-style: solid;
              // border-top-color: #d8d8d8;
              box-shadow: inset 0px 1px 5px 0px rgba(0, 0, 0, 0.3);
              // span {
              //   margin-top: -2px;
              // }
              // box-shadow: inset 0px 2px 2px 1px #bbb;
            }
          }
          .dr-kn-delete {
            color: white;
            /* 表单/单元格描边 */
            box-shadow: 0px 1px 0px 0px #e6e6e6;
            background: #ff7f65;
            border: none;
            border-radius: 4px;
          }
          .dr-kn-submit {
            border: none;
            color: white;

            background: #3689f5;
            /* 表单/单元格描边 */
            box-shadow: 0px 1px 0px 0px #e6e6e6;
            border-radius: 4px;
          }
        }
      }
    }
  }

  .btn-group {
    margin-top: 40px;
    position: relative;
    height: 50px;
    .wh-btn {
      width: 200px;
      height: 50px;
      border-radius: 4px;
      text-align: center;
      line-height: 50px;
      font-size: 18px;
      font-weight: bold;
      color: white;
      position: absolute;

      &.info {
        position: absolute;
        background: #d8d8d8;
        left: 50%;
        transform: translateX(-50%);
      }
      &.primary {
        background: #3689f5;
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
      }
      &.danger {
        position: absolute;
        right: 0px;
        background: white;
        border: 1px solid #ff7f65;
        color: #ff7f65;
        display: flex;
        align-items: center;
        justify-content: center;
        .el-image {
          width: 32px;
          height: 32px;
          margin-right: 10px;
        }
      }
    }
  }
}
</style>
